package cn.kone.system.service.impl;

import cn.kone.system.domain.Employee;
import cn.kone.system.domain.Role;
import cn.kone.system.mapper.EmployeeMapper;
import cn.kone.system.query.EmployeeQuery;
import cn.kone.system.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 查询单个
     *
     * @param id
     * @return
     */
    @Override
    public Employee findOne(Long id) {
        return employeeMapper.findOne(id);
    }

    /**
     * 查询全部
     *
     * @return
     */
    @Override
    public List<Employee> findAll() {
        return employeeMapper.findAll();
    }

    /**
     * 新增单个
     *
     * @param employee
     */
    @Override
    public void addEmployee(Employee employee) {
        //新增员工信息
        employeeMapper.addEmployee(employee);
        //判断这个employee里面的角色id信息里有没有东西,有的话就新增到员工角色中间表
        if(employee.getRoles().size()>0){
            employeeMapper.addEmployeeRole(employee);
        }
    }

    /**
     * 修改单个
     *
     * @param employee
     */
    @Override
    public void updateEmployee(Employee employee) {
        //修改员工信息
        employeeMapper.updateEmployee(employee);
        employeeMapper.deleteRoleEmployeeByEmployeeId(employee.getId());
        //判断这个employee里面的角色id信息里有没有东西,有的话就新增到员工角色中间表
        if(employee.getRoles().size()>0){
            employeeMapper.addEmployeeRole(employee);
        }
    }

    /**
     * 删除单个
     *
     * @param id
     */
    @Override
    public void deleteEmployee(Long id) {
        //先删除中间表,然后再删除员工表
        employeeMapper.deleteRoleEmployeeByEmployeeId(id);
        employeeMapper.deleteEmployee(id);

    }

    /**
     * 高级查询+分页
     *
     * @param employeeQuery
     * @return
     */
    @Override
    public List<Employee> pageQuery(EmployeeQuery employeeQuery) {
        PageHelper.startPage(employeeQuery.getCurrentPage(), employeeQuery.getPageSize());
        List<Employee> employees = employeeMapper.pageQuery(employeeQuery);
        //遍历出每一个员工的角色信息的集合
        for (Employee emp : employees) {
            List<Role> roleList = employeeMapper.getRolesEmployesById(emp.getId());
            //将遍历出来的角色信息存进这个员工信息表中
            emp.setDbRoles(roleList);
        }
        return employees;
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    public void batchDeleteEmployee(Long[] ids) {
        for (Long id : ids) {
            deleteEmployee(id);
        }
    }
}
